import axios from 'axios'
import store from '../store'

const _axios = axios.create({
    baseURL: '/apis',
    timeout: 5000
})

_axios.interceptors.request.use(config=>{
     let token = store.state.common.token
     if(!token){
         if(config.url==='/user/validate/code' || config.url === '/user/app/login'){
            return config
         }else{
            return Promise.reject({code:998,message:'用户非法操作'})
         }
     }else{
        config.headers.token = token
        return config
     }
})

export default req => {
    if (!req) {
        throw new Error('axios request must has some params')
        return
    }
    if (!req.url) {
        throw new Error('axios request must has url params')
        return
    }
    return new Promise(resolve => {

        // if (req.method.toLocalLowercase() === 'post') {
        //     _axios.post()
        // } else if (req.method === 'get') {
        //     _axios.get()
        // } else if (req.method === 'put') {
        //     _axios.put()
        // } else if (req.method === 'delete') {

        // }

        _axios.request({
            url: req.url,
            method: !!req.method ? req.method : 'GET', // 默认值为：get，否则为用户传递的类型
            params: req.params || {}, // 默认值为：Object
            data: req.data || {} // 默认值为：Object
        }).then(({data}) => { // 实际接收到的是 xhr response
            resolve(data)
        }).catch(e => {
            resolve({code: 999, message: 'ajax error'})
        })
    })
}



// return new Promise(resolve => {
    
//     // create(config?: AxiosRequestConfig): AxiosInstance
//     // 使用create方法创建一个实例对象，在创建的时候，默认一些参数
//     let _axios = axios.create({
//         baseURL: '/apis',
//         timeout: 5000,
//     })

//     // 使用request方法来进行ajax请求
//     // request (config: AxiosRequestConfig): Promise

//     if (!req.url) {
//         throw new Error('axios request must has url params')
//         return
//     }

//     _axios.request({
//         url: req.url,
//         method: !!req.method ? req.method : 'GET', // 默认值为：get，否则为用户传递的类型
//         params: req.params || {}, // 默认值为：Object
//         data: req.data || {} // 默认值为：Object
//     }).then(data => {
//         resolve(data)
//     }).catch(e => {
//         console.log(e)
//         resolve({code: 999, message: 'ajax error'})
//     })
// })
// }